package org.lee;

import fr.opensagres.poi.xwpf.converter.core.FileImageExtractor;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.xmlbeans.impl.util.Base64;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;

/**
 * @author jackielee
 * @version 1.0
 * @description App
 * @date 2021/6/1
 */
public class App {

  /**
   * 导出docx到html,同时导出image
   *
   * @param args
   * @throws IOException
   */
  public static void main1(String[] args) throws IOException {
    String fileName = "C:\\Users\\Jackie\\Downloads\\dd\\html\\abcd.docx";
    try (FileInputStream is = new FileInputStream(fileName)) {
      XWPFDocument document = new XWPFDocument(is);
      String outPath = "C:\\Users\\Jackie\\Downloads\\dd\\html\\";
      FileOutputStream outputStream = new FileOutputStream(outPath + "demo.html");
      XHTMLOptions options = XHTMLOptions.create();
      options.setExtractor(new FileImageExtractor(new File(outPath)));
      XHTMLConverter.getInstance().convert(document, outputStream, options);
      document.close();
    }
  }

  /**
   * 导出docx到html base64处理图片
   *
   * @param args
   * @throws IOException
   */
  public static void main2(String[] args) throws IOException {
    String fileName = "C:\\Users\\Jackie\\Downloads\\dd\\html\\abcd.docx";
    try (FileInputStream is = new FileInputStream(fileName)) {
      XWPFDocument document = new XWPFDocument(is);
      String outPath = "C:\\Users\\Jackie\\Downloads\\dd\\html\\";
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      FileOutputStream out = new FileOutputStream(outPath + "abcd.docx.html");
      XHTMLConverter.getInstance().convert(document, outputStream, null);
      String html = setImg(outputStream.toString(), document.getAllPackagePictures());

      OutputStreamWriter writer = new OutputStreamWriter(out);
      writer.write(html);
      writer.flush();
      out.close();
      document.close();
    }
  }

  /**
   * doc转html base64处理图片
   *
   * @param args
   */
  public static void main3(String[] args) {

    String fileName = "C:\\Users\\Jackie\\Downloads\\dd\\html\\abcd.doc";
    try (FileInputStream is = new FileInputStream(fileName)) {
      HWPFDocument document = new HWPFDocument(is);
      WordToHtmlConverter converter =
          new WordToHtmlConverter(
              DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
      converter.setPicturesManager(
          (content, pictureType, suggestedName, widthInches, height) -> {
            String type = pictureType.name();
            return String.format(
                "data:image/%s;base64,%s", type, new String(Base64.encode(content)));
          });

      FileOutputStream out =
          new FileOutputStream("C:\\Users\\Jackie\\Downloads\\dd\\html\\abcd.doc.html");
      OutputStreamWriter writer = new OutputStreamWriter(out);
      converter.processDocument(document);
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.METHOD, "html");
      transformer.transform(new DOMSource(converter.getDocument()), new StreamResult(writer));
      writer.flush();
      out.close();
      document.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }
  }

  private static String setImg(String html, List<XWPFPictureData> list) {
    Document doc = Jsoup.parse(html);
    Elements elements = doc.getElementsByTag("img");
    if (elements != null && elements.size() > 0 && list != null) {
      for (Element element : elements) {
        String src = element.attr("src");
        for (XWPFPictureData data : list) {
          if (src.contains(data.getFileName())) {
            String type = src.substring(src.lastIndexOf(".") + 1);
            String base64 =
                String.format(
                    "data:image/%s;base64,%s", type, new String(Base64.encode(data.getData())));
            element.attr("src", base64);
            break;
          }
        }
      }
    }

    return doc.toString();
  }

  static void exportImages(XWPFDocument doc, String path) throws IOException {
    for (XWPFPictureData pic : doc.getAllPackagePictures()) {
      FileOutputStream fout = new FileOutputStream(String.format("%s/%s", path, pic.getFileName()));
      fout.write(pic.getData());
      fout.close();
    }
  }
}
